package shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     *
     * 头信息具有sessionId
     *
     *  请求头： Authorization: sessionId
     *
     * 指定sessionId的方法
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        // 获取请求头中的数据
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if(StringUtils.isEmpty(id)){
            // 如果没有携带，生成新的sessionId
            return super.getSessionId(request, response);
        }else{
            // 请求头信息为 bearer sessionid
            id = id.replaceAll("Bearer ", "");
            // 返回sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");// id从哪里获取到的
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);// sessionId 的值
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);// sessionId是否需要验证
            return id;
        }

    }
}
